package asyncTasks;

import java.io.IOException;

import android.os.AsyncTask;
import android.util.Log;
import basicClasses.PlaceDetails;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;

public class PlaceDetailRequest extends AsyncTask<String, Void, PlaceDetails> {

	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
	
	@Override
	protected PlaceDetails doInBackground(String... args) {
		try {
			HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
            HttpRequest request;
				request = httpRequestFactory
				        .buildGetRequest(new GenericUrl("https://maps.googleapis.com/maps/api/place/details/json?"));
	            request.getUrl().put("key", "AIzaSyDspt3tRVqb0O0QhXhyn07AiVFWiB0mF40");
	            request.getUrl().put("reference", args[0]);
	            request.getUrl().put("sensor", "false");
	            
	            PlaceDetails placeDetails = request.execute().parseAs(PlaceDetails.class);
	            // Check log cat for places response status
	          
	            return placeDetails;
 
        } catch (HttpResponseException e) {
            Log.e("Error:", e.getMessage());
            return null;
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

}

public static HttpRequestFactory createRequestFactory(
        final HttpTransport transport) {
    return transport.createRequestFactory(new HttpRequestInitializer() {
        public void initialize(HttpRequest request) {
            GoogleHeaders headers = new GoogleHeaders();
            headers.setApplicationName("AndroidHive-Places-Test");
            request.setHeaders(headers);
            JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
            request.addParser(parser);
        }
    });
}

}